﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Musicman.Common.Entities;
using Musicman.Business;
using Musicman.Common.Utilities;

namespace Musicman.Client2
{
    public partial class StatisticsForm : Form
    {
        
        public StatisticsForm()
        {
            InitializeComponent();
            KeyPreview = true;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                this.Hide();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        public void RefreshData()
        {
            List<SearchJob> jobs = SearchJobManager.Instance.LoadAllSearchJobs();
            List<User> topLoggers = UserManager.Instance.LoadTopLoggers(5);
            List<User> topDownloaders = UserManager.Instance.LoadTopDownloaders(5);

            dgvJobStats.Rows.Clear();
            foreach (SearchJob job in jobs)
            {
                dgvJobStats.Rows.Add(new object[] { job.Name, job.AllCriteria, job.StartTime, job.EndTime, job.TotalFiles, job.TotalLength });
            }
            dgvTopLoggers.Rows.Clear();
            foreach (User user in topLoggers)
            {
                dgvTopLoggers.Rows.Add(new object[] {String.Format("{0} {1}", user.Firstname, user.Lastname), 
                    user.UserStats.TotalLogsWeb, user.UserStats.TotalLogsCient, 
                    user.UserStats.TotalLogsWeb + user.UserStats.TotalLogsCient});
            }
            dgvTopDownloaders.Rows.Clear();
            foreach (User user in topLoggers)
            {
                dgvTopDownloaders.Rows.Add(new object[] {String.Format("{0} {1}", user.Firstname, user.Lastname), 
                    user.UserStats.TotalFilesDownloaded, Converter.LengthGB(user.UserStats.TotalFilesLength)});
            }
        }

        private void dgvJobStats_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv["TotalLength", e.RowIndex].Value.GetType() != typeof(String))
            {
                long totalLength = (long)dgv["TotalLength", e.RowIndex].Value;
                dgv["TotalLength", e.RowIndex].Value = Converter.LengthGB(totalLength);
            }
        }

    }
}
